<?php
namespace Leaps\Cache\Adapter;

use Leaps\Redis\Database as Redis1;
use Leaps\Cache\AdapterInterface;
use Leaps\Cache\RedisSection;

class Redis implements AdapterInterface {

	/**
	 * The Redis database connection.
	 *
	 * @var \Leaps\Redis\Database
	 */
	protected $redis;

	/**
	 * Create a new Redis store.
	 *
	 * @param  \Leaps\Redis\Database  $redis
	 * @param  string                     $prefix
	 * @return void
	 */
	public function __construct(Redis1 $redis)
	{
		$this->redis = $redis;
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::get()
	 */
	public function get($key)
	{
		if ( ! is_null($value = $this->redis->get($key)))
		{
			return is_numeric($value) ? $value : unserialize($value);
		}
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::set()
	 */
	public function set($key, $value, $minutes)
	{
		$value = is_numeric($value) ? $value : serialize($value);
		$this->redis->set($key, $value);
		$this->redis->expire($key, $minutes * 60);
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::forever()
	 */
	public function forever($key, $value)
	{
		$value = is_numeric($value) ? $value : serialize($value);
		$this->redis->set($key, $value);
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::delete()
	 */
	public function delete($key)
	{
		$this->redis->del($key);
	}

	/**
	 * (non-PHPdoc)
	 * @see \Leaps\Cache\StoreInterface::flush()
	 */
	public function flush()
	{
		$this->redis->flushdb();
	}

	/**
	 * Begin executing a new section operation.
	 *
	 * @param  string  $name
	 * @return \Leaps\Cache\Section
	 */
	public function section($name)
	{
		return new RedisSection($this, $name);
	}

	/**
	 * Get the Redis database instance.
	 *
	 * @return \Leaps\Redis\Database
	 */
	public function getRedis()
	{
		return $this->redis;
	}
}